import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/page/user/edit/xmm_user_edit_controller.dart';
import 'package:bigegg/utils/dialog/xmm_dialog_utils.dart';
import 'package:bigegg/widget/image/xmm_circle_cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../common/log/xmm_log.dart';
import '../../../utils/xmm_media_utils.dart';
import '../../../widget/xmm_widget.dart';

class XmmUserEditPage extends StatefulWidget {
  const XmmUserEditPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return XmmUserEditPageState();
  }
}

class XmmUserEditPageState extends State<XmmUserEditPage> {
  final XmmUserEditController controller = Get.find<XmmUserEditController>();

  final TextEditingController _nikeNameController = TextEditingController(
    text: XmmAccountManager.instance.user.nickname,
  );

  final isCanSubmit = false.obs;

  final birthday = DateTime.parse(
    XmmAccountManager.instance.user.birthday ?? DateTime.now().toString(),
  ).obs;

  @override
  void initState() {
    super.initState();
  }

  void updateCanSubmitStatus() {
    var nickname = _nikeNameController.text;
    var oldBirthday =
        DateTime.parse(XmmAccountManager.instance.user.birthday ?? "");
    if (nickname == XmmAccountManager.instance.user.nickname &&
        birthday.value == oldBirthday) {
      isCanSubmit.value = false;
    } else {
      isCanSubmit.value = true;
    }
  }
  void editAvatar() async {
    List list = [
      {
        'title': 'Take a picture',
        'onPressed': () async {
          String? imgPath = await XmmMediaUtils.takePhoto();
          if (imgPath != null) {
            controller.editAvatar(imgPath);
          }
        },
      },
      {
        'title': 'Photo album',
        'onPressed': () async {
          String? imgPath = await XmmMediaUtils.pickImage();
          if (imgPath != null) {
            controller.editAvatar(imgPath);
          }
        },
      }
    ];
    XmmDialogUtils.showSelectDialog(list);
  }

  void editBirthday() {
    DateTime maximumDate =
        DateTime.now().subtract(const Duration(days: 365 * 18));
    XmmDialogUtils.showDatePicker(
      initialDateTime: birthday.value,
      maximumDate: maximumDate,
      onDateTimeChanged: (value) {
        birthday.value = value;
        updateCanSubmitStatus();
      },
    );
  }

  void submit() async {
    if (isCanSubmit.value) {
      controller.submitUserInfo(_nikeNameController.text, birthday.value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: commonBgDecoration(),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            toolBarWidget(context, ""),
            Stack(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 90.w, left: 20.w),
                  child: Image.asset(
                    "assets/images/xmm_icon_about.png",
                    height: 91.w,
                  ),
                ),
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                    margin: EdgeInsets.only(top: 70.w),
                    child: GestureDetector(
                      child: Stack(
                        alignment: AlignmentDirectional.topCenter,
                        children: [
                          Container(
                            padding: EdgeInsets.only(bottom: 13.w),
                            child: Obx(
                              () => XmmCircleCachedNetworkImage(
                                imageUrl: XmmAccountManager.instance.user.avatarUrl ?? "",
                                height: 98.w,
                                width: 98.w,
                                borderColor: Colors.white,
                                borderWidth: 2,
                              ),
                            ),
                          ),
                          Positioned(
                            bottom: 0,
                            child: Image.asset(
                              "assets/images/xmm_icon_avatar_camera.png",
                              height: 26.w,
                              width: 26.w,
                            ),
                          )
                        ],
                      ),
                      onTap: () async => editAvatar(),
                    ),
                  ),
                )
              ],
            ),
            SizedBox(height: 49.w),
            Container(
              margin: EdgeInsets.only(left: 24.w, right: 24.w),
              padding: EdgeInsets.only(left: 28.w, right: 28.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  SizedBox(height: 24.w),
                  Row(
                    children: [
                      Text(
                        "Nick Name",
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: const Color(0x4D000000),
                        ),
                      ),
                      Expanded(
                        child: TextField(
                          controller: _nikeNameController,
                          decoration: const InputDecoration(
                            contentPadding: EdgeInsets.zero,
                            isDense: true,
                            border: OutlineInputBorder(
                              borderSide: BorderSide.none,
                              borderRadius: BorderRadius.only(),
                              gapPadding: 0.0,
                            ),
                          ),
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: const Color(0xFF404040),
                          ),
                          textAlign: TextAlign.right,
                          onChanged: (value) => updateCanSubmitStatus(),
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 12.w),
                  Container(
                    height: 1,
                    color: const Color(0xFFEEEEEE),
                  ),
                  SizedBox(height: 20.w),
                  Row(
                    children: [
                      Text(
                        "Date of Birth",
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: const Color(0x4D000000),
                        ),
                      ),
                      const Expanded(child: SizedBox()),
                      GestureDetector(
                        child: Obx(
                          () => Text(
                            '${birthday.value.year}-${birthday.value.month}-${birthday.value.day}',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: const Color(0xFF404040),
                            ),
                          ),
                        ),
                        onTap: () => editBirthday(),
                      )
                    ],
                  ),
                  SizedBox(height: 12.w),
                  Container(
                    height: 1,
                    color: const Color(0xFFEEEEEE),
                  ),
                  SizedBox(height: 44.w),
                  GestureDetector(
                    child: Obx(
                      () => Container(
                        alignment: Alignment.center,
                        width: 182.w,
                        height: 38.w,
                        decoration: BoxDecoration(
                          color: isCanSubmit.value
                              ? const Color(0xFF15E8C2)
                              : const Color(0xFFA0A0A0),
                          borderRadius: BorderRadius.circular(39),
                        ),
                        child: Text(
                          "Submit",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                          ),
                        ),
                      ),
                    ),
                    onTap: () async => submit(),
                  ),
                  SizedBox(height: 24.w),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
